package com.hmall.search;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.cliet.ItemCliet;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.SearchItem;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class FeingSearch {

    @Autowired
    private ItemCliet itemCliet;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Test
    public void testQuery() throws IOException {
        int page = 1;
        while (true) {
            PageDTO<Item> pageDTO = itemCliet.itemQueryPage(page, 500);
            List<Item> list = pageDTO.getList();
            if (list.size() <= 0) {
                return;
            }
            BulkRequest request = new BulkRequest();
            for (Item item : list) {
                SearchItem searchItem = new SearchItem(item);
                request.add(new IndexRequest("item")
                        .id(searchItem.getId().toString())
                        .source(MAPPER.writeValueAsString(searchItem), XContentType.JSON)
                );
            }
            BulkResponse responses = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            page++;
        }
    }
}
